package com.lt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.reggie.common.R;
import com.lt.reggie.dto.DishDto;
import com.lt.reggie.dto.SetmealDto;
import com.lt.reggie.entity.Category;
import com.lt.reggie.entity.Dish;
import com.lt.reggie.entity.Setmeal;
import com.lt.reggie.entity.SetmealDish;
import com.lt.reggie.service.CategoryService;
import com.lt.reggie.service.DishService;
import com.lt.reggie.service.SetmealDishService;
import com.lt.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Queue;
import java.util.concurrent.Semaphore;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealDishController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        setmealService.saveWithDish(setmealDto);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime).orderByAsc(Setmeal::getCreateTime);
        //执行分页查询
        setmealService.page(pageInfo, queryWrapper);
        //对象拷贝                                                   //数据不进行拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> setmeals = pageInfo.getRecords();
        List<SetmealDto> dtoList = setmeals.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //将item中的对象属性拷贝到stemealDto对象中
            BeanUtils.copyProperties(item, setmealDto);
            //根据套餐分类id查出分类名
            Long categoryId = item.getCategoryId();//套餐分类id
            Category category = categoryService.getById(categoryId);//套餐分类对象
            //判断返回的对象是否为空
            if (category != null) {
                String categoryName = category.getName();//套餐分类名
                setmealDto.setCategoryName(categoryName);//添加套餐分类名
            }
            return setmealDto;
        }).collect(Collectors.toList());
        //将封装好的dtoList集合添加到dtoPage中
        dtoPage.setRecords(dtoList);
        return R.success(dtoPage);
    }

    /**
     * 删除或批量删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info(ids.toString());
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        List<Setmeal> list = setmealService.list(queryWrapper);
        for (Setmeal setmeal : list) {
            if (setmeal.getStatus() != 0) {
                return R.error(ids.size() > 1 ? "当前选中的套餐中有正在出售中的,不能删除" : "当前套餐正在出售中,不能删除");
            }
        }
        setmealService.deleteByIdsWithDish(ids);

        return R.success("删除成功");
    }

    /**
     * 停售或批量停售
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> status(@PathVariable int status, @RequestParam List<Long> ids) {
        log.info("status = {},ids = {}", status, ids.toString());
        Setmeal setmeal = new Setmeal();
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        setmeal.setStatus(status);
        setmealService.update(setmeal, queryWrapper);
        return R.success("操作成功");
    }

    /**
     * 根据条件查询套餐数据
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.eq(Setmeal::getStatus, setmeal.getStatus());

        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);
    }

    /**
     * 根据套餐id查询套餐信息
     *
     * @param id
     * @return
     */
    /*@GetMapping("/{id}")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<SetmealDto> getById(@PathVariable("id") Long id) {
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null, SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();

        if (setmeal != null) {
            BeanUtils.copyProperties(setmeal, setmealDto);
            setmealDto.setSetmealDishes(setmealDishList);
            return R.success(setmealDto);
        }
        return R.error(null);
    }*/
    /**
     * 回显套餐
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    /*@Cacheable(value = "setmealCache", key = "#setmealDto.categoryId + '_' + #setmealDto.status")*/
    public R<SetmealDto> getById(@PathVariable Long id) {
//        查询套餐表
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
//        查询套餐关联表
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null, SetmealDish::getSetmealId, id);
        List<SetmealDish> dishList = setmealDishService.list(queryWrapper);

        setmealDto.setSetmealDishes(dishList);
        return R.success(setmealDto);
    }


//    public R<String> update()


    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
//    当修改数据或添加数据时清除缓存
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto) {

        log.info("setmealDto:{}", setmealDto);
//        修改套餐表
        setmealService.updateById(setmealDto);

//        修改套餐关联表
        Long id = setmealDto.getId();
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,id);
        setmealDishService.remove(wrapper);

//        保存提交过来的数据

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        List<SetmealDish> setmealDishList = setmealDishes.stream().map(item -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());


        setmealDishService.saveBatch(setmealDishes);

        return R.success("修改套餐成功");
    }


    /**
     * 查询套餐中的菜品
     *
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> getDish(@PathVariable("id") Long id) {
        //根据套餐id查询套餐中的菜品
        LambdaQueryWrapper<SetmealDish> sdqw = new LambdaQueryWrapper<>();
        sdqw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(sdqw);
        List<DishDto> dishDtoList = setmealDishList.stream().map((item) -> {
            //根据菜品id查询对象菜品对象
            Long dishId = item.getDishId();
            Dish dish = dishService.getById(dishId);
            DishDto dishDto = new DishDto();
            //对象拷贝,将dish对象中的数据拷贝到dishDto中
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setCopies(item.getCopies());
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }
}
